const express = require("express");

const pool = require("../pool.js");

// 加载MD5模块
const md5 = require("md5");

const r = express.Router();

// 用户注册
r.post("/register", (req, res) => {
  // 获取账号
  let uname = req.body.uname;
  // 获取密码
  let upwd = req.body.upwd;
  // 获取昵称
  let unickname = req.body.unickname;
  // 以username为条件进行查找操作，以确保账号的唯一性
  let unameSql = "SELECT COUNT(uid) as count FROM user WHERE uname=?;";
  pool.query(unameSql, [uname], (err, unameResult) => {
    if (err) throw err;
    // 将查询出来的数量结果赋值给新变量
    let unameCount = unameResult[0].count;
    // 判断得出的结果是否为0
    // 为0则代表没有人用此uname注册过
    if (unameCount == 0) {
      // 如果说uname没被注册过，判断昵称是否已被占用
      let unicknameSql =
        "SELECT COUNT(uid) as count FROM user WHERE unickname=?;";
      pool.query(unicknameSql, [unickname], (err, unicknameResult) => {
        if (err) throw err;
        // 将查询出来的数量结果赋值给新变量，用来判断昵称是否已被占用
        let unicknameCount = unicknameResult[0].count;
        if (unicknameCount == 0) {
          let insertSql =
            "INSERT INTO USER(uname,unickname,upwd) VALUES(?,?,MD5(?));";
          pool.query(
            insertSql,
            [uname, unickname, upwd],
            (err, registerResult) => {
              if (err) throw err;
              res.send({ code: 200, msg: "register ok" });
            }
          );
        } else {
          res.send({ code: 202, msg: "unickname exists" });
        }
      });
    } else {
      // 为1则代表有人用此uname注册过
      // 向前台发送uname已被注册
      res.send({ code: 201, msg: "uname exists" });
    }
  });
});

// 用户登录
r.post("/login", (req, res) => {
  let uname = req.body.uname;
  let upwd = req.body.upwd;

  let sql = "SELECT * FROM user WHERE uname=? AND upwd=MD5(?);";
  pool.query(sql, [uname, upwd], (err, result) => {
    if (err) throw err;
    console.log(result);
    if (result.length == 0) {
      res.send({ code: 201, msg: "login failed" });
    } else {
      res.send({ code: 200, msg: "ok", loginResult: result[0] });
    }
  });
});
module.exports = r;
